package com.bdth.bdthiss.plus;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.interactions.Actions;

public class Cookies {

    public static List<Integer> back_tracks = new ArrayList<>();

    /**
     * @author Young
     *
     */
    public static void addCookies() throws Exception{

        WebDriver driver = DriverFactory.create();
        driver.get("https://login.tmall.com/");
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

        //模拟点击到账号密码登陆
        driver.findElement(By.id("fm-login-password")).click();
        Thread.sleep(1000);
        driver.manage().window().maximize();
        //driver.findElement(By.id("J_Quick2Static")).click();
        driver.findElement(By.id("fm-login-id")).sendKeys("13285202553");
        Thread.sleep(1000);
        driver.findElement(By.id("fm-login-password")).sendKeys("bdth1234");
        Thread.sleep(1000);
        WebElement nc_1_n1z = driver.findElement(By.id("nc_1_n1z"));
        Actions actions = new Actions(driver);
        actions.clickAndHold(nc_1_n1z);
        Random ra =new Random();
        actions.dragAndDropBy(nc_1_n1z,500,0);
        Thread.sleep(200+ ra.nextInt(400));

        for (Integer back_track : back_tracks) {
            int yoffset_random = ra.nextInt(4) - 2;
            actions.moveByOffset(back_track, yoffset_random).perform();
        }


        int x = ra.nextInt(3) - 4;
        int y = ra.nextInt(4) - 2;
        actions.moveByOffset(x, y).perform();
        x = ra.nextInt(2) +1;
        y = ra.nextInt(4) - 2;
        actions.moveByOffset(x, y).perform();
        Thread.sleep(200+ ra.nextInt(400));
        driver.findElement(By.className("password-login")).click();

        Thread.sleep(3000);

        File file = new File("broswer.data");
        try {
            // delete file if exists
            file.delete();
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for (Cookie ck : driver.manage().getCookies()) {
                bw.write(ck.getName() + ";" + ck.getValue() + ";"
                        + ck.getDomain() + ";" + ck.getPath() + ";"
                        + ck.getExpiry() + ";" + ck.isSecure());
                bw.newLine();
            }
            bw.flush();
            bw.close();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("cookie write to file");
        }
    }
}
